package com.huike.pmps.utils;

import com.huike.pmps.model.entity.Permission;
import com.huike.pmps.model.vo.security.MenuVo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
public class TreeMenusUtil {

    /**
     * 创建树结构
     *
     * @return
     */
    public static List<MenuVo> tree(List<Permission> permissionSet) {
        //返回的节点树
        List<MenuVo> rootMenus = new ArrayList<>();

        Iterator<Permission> it = permissionSet.iterator();
        while (it.hasNext()) {
            Permission p = it.next();
            //parent（上级Id）为0的是根节点
            if (p.getParentId() == 0) {
                MenuVo menuVo = MenuVo.builder().id(p.getId()).resourceName(p.getResourceName()).resourceUrl(p.getResourceUrl()).parentId(p.getParentId()).icon(p.getIcon()).build();
                rootMenus.add(menuVo);
                it.remove();
            }
        }
        //遍历，找到二级节点
        for (MenuVo vo : rootMenus) {
            List<MenuVo> child = getChild(permissionSet, vo.getId());
            vo.setChildMenu(child);
        }
        return rootMenus;

    }

    /**
     * 查子节点
     *
     * @param parentId
     * @return
     */
    private static  List<MenuVo> getChild(List<Permission> permissionSet, int parentId) {
        //子节点列表
        List<MenuVo> childList = new ArrayList<>();
        Iterator<Permission> it = permissionSet.iterator();
        while (it.hasNext()) {
            Permission p = it.next();
            //parent（上级Id）为0的是根节点
            if (p.getParentId() == parentId) {
                MenuVo menuVo = MenuVo.builder().id(p.getId()).resourceName(p.getResourceName()).resourceUrl(p.getResourceUrl()).parentId(p.getParentId()).icon(p.getIcon()).build();
                childList.add(menuVo);
                it.remove();
            }
        }
        //遍历 递归获取子节点的子节点
        for (MenuVo vo : childList) {
            List<MenuVo> child = getChild(permissionSet, vo.getId());
            vo.setChildMenu(child);
        }
        //递归出口  childList长度为0
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }
}
